package com.zxc.reggie.controller;

import com.zxc.reggie.common.BaseContext;
import com.zxc.reggie.common.R;
import com.zxc.reggie.entity.AddressBook;
import com.zxc.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/addressBook")
public class AddressBookController {

    @Resource
    private AddressBookService addressBookService;

    @RequestMapping("/list")
    public R<List<AddressBook>> listR() {

        List<AddressBook> list = addressBookService.list();
        return R.success(list);
    }

    @PutMapping("/default")

    public R<String> updateDefaultAdd(@RequestBody Map<String, Long> map) {
        Long addressBookId = map.get("id");
        addressBookService.update().eq("is_default", 1).setSql(" is_default = 0 ").update();
        addressBookService.update().setSql(" is_default = 1 ").eq("id", addressBookId).update();
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<AddressBook> findAddressBook(@PathVariable String id) {

        AddressBook addressBook = addressBookService.query().eq("id", id).one();
        return R.success(addressBook);
    }

    @PutMapping()

    public R<String> update(@RequestBody AddressBook addressBook) {
     addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
    @GetMapping("/default")

    public R<AddressBook> findDefaultAdd(){

        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookService.query().eq("user_id", userId).eq("is_default", 1).one();

        return R.success(addressBook);
    }
}
